package ProducerConsumer;

/**
 * @program: javase
 * @description: 生产者消费者问题-管程法
 * @author: lld
 * @create: 2021-03-22 16:54
 **/
public class TubeTest {
    public static void main(String[] args) {
        SysContainer container = new SysContainer();
        new Producer(container).start();
        new Consumer(container).start();
    }
}
//生产者
class Producer extends Thread{
    SysContainer container;

    public Producer(SysContainer container) {
        this.container = container;
    }

    //只顾生产
    @Override
    public void run() {
        for (int i = 0; i <100 ; i++) {
            container.push(new Thing(i));
            System.out.println("生产了===>第"+i+"个thing");
        }
    }

}
//消费者
class Consumer extends Thread{
    SysContainer container;

    public Consumer(SysContainer container) {
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i <100 ; i++) {
            container.pop();
            System.out.println("消费了<<<<<===第"+i+"个thing");
        }
    }
}
//产品
class Thing{
    int id;

    public Thing(int id) {
        this.id = id;
    }
}
//缓冲区
class SysContainer{
    //缓冲大小,数组长度为10，只有things[9]
    Thing[] things=new Thing[10];
    //计数器
    int count=0;
    //生产者生成放入缓冲区
    public synchronized void push(Thing thing){
        if(things.length==count){
            //等待，通知消费者消费
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //放入
        things[count]=thing;
        count++;
        //通知消费者消费
        this.notifyAll();
    }
    //消费者取出
    public synchronized Thing pop(){
        if(count==0){
            //等待，通知生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        //消费一个
        Thing thing=things[count];
        //通知生产者生产
        this.notifyAll();
        return thing;
    }
}
